package com.azh.server.transport;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

/**
 * @author zhaozhenhang <zhaozhenhang@kuaishou.com>
 * Created on 2022-05-02
 * 这儿简单处理特殊字符造成的问题，将数据转化为16进制字符串（Hex String）
 * 并未信息末尾加上换行符，这样发送和接收时，直接按行读写
 */
public class Transporter {

    private Socket socket;

    private BufferedReader reader;

    private BufferedWriter writer;

    public Transporter(Socket socket) throws IOException {
        this.socket = socket;
        this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    }

    public void send(byte[] data) throws Exception {
        String raw = hexEncode(data);
        writer.write(raw);
        writer.flush();
    }

    public byte[] receive() throws Exception {
        String line = reader.readLine();
        if (line == null) {
            close();
        }
        return hexDecode(line);
    }

    public void close() throws IOException {
        writer.close();
        reader.close();
        socket.close();
    }

    private String hexEncode(byte[] buffer) {
        return Hex.encodeHexString(buffer, true) + "\n";
    }

    private byte[] hexDecode(String raw) throws DecoderException {
        return Hex.decodeHex(raw);
    }

}
